package cn.zd.demo1;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import java.util.List;
import java.util.Random;

import cn.zd.demo1.sql.MyRoomDatabases;
import cn.zd.demo1.sql.entity.TabUserInfoEntity;
import cn.zd.demo1.util.StringUtil;
import cn.zd.demo1.util.ViewCheckUtil;

public class RoomActivity extends AppCompatActivity implements View.OnClickListener {
    EditText et_db;
    EditText et_username;
    EditText et_usernamenew;
    EditText et_trans_username;
    EditText et_trans_userage;
    CheckBox cb_trans_flag;
    Button btn_insertuser;
    Button btn_queryuser;
    Button btn_queryalluser;
    Button btn_deluser;
    Button btn_delall;
    Button btn_updateuser;
    Button btn_updateuserall;
    Button btn_trans_test;
    TextView tv_userinfo;
    private MyRoomDatabases roomDatabases;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        Toast.makeText(this, this.getClass().getName(), Toast.LENGTH_LONG).show();

        et_username = findViewById(R.id.et_username);
        et_usernamenew = findViewById(R.id.et_usernamenew);
        et_trans_username = findViewById(R.id.et_trans_username);
        et_trans_userage = findViewById(R.id.et_trans_userage);

        tv_userinfo = findViewById(R.id.tv_userinfo);

        btn_insertuser = findViewById(R.id.btn_insertuser);
        btn_queryuser = findViewById(R.id.btn_queryuser);
        btn_queryalluser = findViewById(R.id.btn_queryalluser);
        btn_updateuser = findViewById(R.id.btn_updateuser);
        btn_updateuserall = findViewById(R.id.btn_updateuserall);
        btn_deluser = findViewById(R.id.btn_deluser);
        btn_delall = findViewById(R.id.btn_delall);
        btn_trans_test = findViewById(R.id.btn_trans_test);
        cb_trans_flag = findViewById(R.id.cb_trans_flag);

        btn_insertuser.setOnClickListener(this);
        btn_queryuser.setOnClickListener(this);
        btn_updateuser.setOnClickListener(this);
        btn_updateuserall.setOnClickListener(this);
        btn_queryalluser.setOnClickListener(this);
        btn_deluser.setOnClickListener(this);
        btn_delall.setOnClickListener(this);
        btn_trans_test.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {


       if (v.getId() == R.id.btn_insertuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            TabUserInfoEntity userInfo = new TabUserInfoEntity();
            userInfo.setUserAge(new Random().nextInt(100));
            userInfo.setUserName(userName);
            roomDatabases.tabUserInfoDao().insert(userInfo);
            tv_userinfo.setText("插入数据\n" + userInfo.toString());
            Toast.makeText(this, "用户数据插入成功", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_queryuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            List<TabUserInfoEntity> userInfos = roomDatabases.tabUserInfoDao().queryByName(oldUserName);
            Toast.makeText(this, "查询所有用户数:" + userInfos.size(), Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询指定用户名" + oldUserName + "数据\n" + StringUtil.listToString(userInfos));

        } else if (v.getId() == R.id.btn_queryalluser) {
            List<TabUserInfoEntity> userInfos = roomDatabases.tabUserInfoDao().queryAll();
            Toast.makeText(this, "查询所有用户数:" + userInfos.size(), Toast.LENGTH_SHORT).show();
            tv_userinfo.setText("查询所有数据\n" + StringUtil.listToString(userInfos));
        } else if (v.getId() == R.id.btn_updateuser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            if (!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this, "请输入新用户名", Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String oldUserName = et_username.getText().toString();
            String newUserName = et_usernamenew.getText().toString();

            roomDatabases.tabUserInfoDao().update(newUserName, oldUserName);
            Toast.makeText(this, "用户数据更新成功", Toast.LENGTH_SHORT).show();

        } else if (v.getId() == R.id.btn_updateuserall) {
            if (!ViewCheckUtil.checkEditText(et_usernamenew)) {
                Toast.makeText(this, "请输入新用户名", Toast.LENGTH_SHORT).show();
                et_usernamenew.requestFocus();
                return;
            }
            String newUserName = et_usernamenew.getText().toString();
            roomDatabases.tabUserInfoDao().updateAll(newUserName);
            Toast.makeText(this, "用户数据更新成功", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_deluser) {
            if (!ViewCheckUtil.checkEditText(et_username)) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                et_username.requestFocus();
                return;
            }
            String userName = et_username.getText().toString();
            roomDatabases.tabUserInfoDao().deleteByName(userName);
            Toast.makeText(this, "用户数据删除成功:", Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_delall) {
            long res = roomDatabases.tabUserInfoDao().deleteAll();
            Toast.makeText(this, "所有用户数据删除结果:" + res, Toast.LENGTH_SHORT).show();
        } else if (v.getId() == R.id.btn_trans_test) {
            if (!ViewCheckUtil.checkEditText(et_trans_username)) {
                Toast.makeText(this, "请输入姓名", Toast.LENGTH_SHORT).show();
                et_trans_username.requestFocus();
                return;
            }
            if (!ViewCheckUtil.checkEditText(et_trans_userage)) {
                Toast.makeText(this, "请输入年纪", Toast.LENGTH_SHORT).show();
                et_trans_userage.requestFocus();
                return;
            }
            boolean rollback = cb_trans_flag.isChecked();
            TabUserInfoEntity trans = new TabUserInfoEntity();
            trans.setUserName(et_trans_username.getText().toString());
            trans.setUserAge(Integer.parseInt(et_trans_userage.getText().toString()));

            try {
                roomDatabases.runInTransaction(() -> {
                    roomDatabases.tabUserInfoDao().insert(trans);
                    if (rollback) {
                        Toast.makeText(this, "异常中断，两条数据都将不会保存", Toast.LENGTH_SHORT).show();
                        throw new RuntimeException("回滚异常测试！");
                    }
                    trans.setUserName(trans.getUserName() + "-copy");
                    trans.setUserAge(trans.getUserAge() * 2);
                    roomDatabases.tabUserInfoDao().insert(trans);
                    Toast.makeText(this, "正常测试,两条数据都将保存", Toast.LENGTH_SHORT).show();
                });
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }



    @Override
    protected void onStart() {
        super.onStart();
        Toast.makeText(this, "数据库打开成功", Toast.LENGTH_SHORT).show();
        roomDatabases = Room.databaseBuilder(this, MyRoomDatabases.class, "demo1userentity")
                //  允许迁移数据库（发生数据变更时，默认删除原数据库然后再重新创建，数据就会丢失，改为迁移则可保留数据）
                .addMigrations()
                // 默认不允许主线程操作
                .allowMainThreadQueries()
                .build();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}